package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.domain.AttendanceRecord;
import com.ruoyi.common.domain.Emply;
import com.ruoyi.common.domain.Holidays;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.enums.EDirection;
import com.ruoyi.common.enums.ERecordType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Statistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.KqCardRecordMapper;
import com.ruoyi.system.domain.KqCardRecord;
import com.ruoyi.system.service.IKqCardRecordService;

/**
 * 打卡原始记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-03-18
 */
@Service
public class KqCardRecordServiceImpl implements IKqCardRecordService 
{
    @Autowired
    private KqCardRecordMapper kqCardRecordMapper;

    /**
     * 查询打卡原始记录
     * 
     * @param recordId 打卡原始记录主键
     * @return 打卡原始记录
     */
    @Override
    public KqCardRecord selectKqCardRecordByRecordId(Long recordId)
    {
        return kqCardRecordMapper.selectKqCardRecordByRecordId(recordId);
    }

    /**
     * 查询打卡原始记录列表
     * 
     * @param kqCardRecord 打卡原始记录
     * @return 打卡原始记录
     */
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<KqCardRecord> selectKqCardRecordList(KqCardRecord kqCardRecord)
    {
        List<KqCardRecord> kqCardRecords = kqCardRecordMapper.selectKqCardRecordList(kqCardRecord);

        kqCardRecords.forEach(p -> {
            p.setRecordTypeString(ERecordType.getInfoByCode(p.getRecordType()));
            p.setDirectionString(EDirection.getInfoByCode(p.getDirection()));
        });
        return kqCardRecords;
    }

    /**
     * 新增打卡原始记录
     * 
     * @param kqCardRecord 打卡原始记录
     * @return 结果
     */
    @Override
    public int insertKqCardRecord(KqCardRecord kqCardRecord)
    {
        return kqCardRecordMapper.insertKqCardRecord(kqCardRecord);
    }

    /**
     * 修改打卡原始记录
     * 
     * @param kqCardRecord 打卡原始记录
     * @return 结果
     */
    @Override
    public int updateKqCardRecord(KqCardRecord kqCardRecord)
    {
        kqCardRecord.setUpdateTime(DateUtils.getNowDate());
        return kqCardRecordMapper.updateKqCardRecord(kqCardRecord);
    }

    /**
     * 批量删除打卡原始记录
     * 
     * @param recordIds 需要删除的打卡原始记录主键
     * @return 结果
     */
    @Override
    public int deleteKqCardRecordByRecordIds(Long[] recordIds)
    {
        return kqCardRecordMapper.deleteKqCardRecordByRecordIds(recordIds);
    }

    /**
     * 删除打卡原始记录信息
     * 
     * @param recordId 打卡原始记录主键
     * @return 结果
     */
    @Override
    public int deleteKqCardRecordByRecordId(Long recordId)
    {
        return kqCardRecordMapper.deleteKqCardRecordByRecordId(recordId);
    }

    @Override
    public List<Statistics> getStatisticsRecord(KqCardRecord kqCardRecord) {
        return kqCardRecordMapper.getStatisticsRecord(kqCardRecord);
    }

    @Override
    public List<Statistics> getStatisticsRecord2(KqCardRecord kqCardRecord) {
        return kqCardRecordMapper.getStatisticsRecord2(kqCardRecord);
    }

    @Override
    public List<Statistics> currentExport(KqCardRecord kqCardRecord, Holidays holidays, List<Emply> emplyList, List<AttendanceRecord> attendAnceInfoList) {
        List<Statistics> attendanceStatisticsList = new Vector<>();


        if(attendAnceInfoList != null && attendAnceInfoList.size() > 0){

            //所有人员考勤
            Map<String, List<AttendanceRecord>> deptGroupInfo = attendAnceInfoList.stream().collect(Collectors.groupingBy(AttendanceRecord::getSysNo));
            //所有人员
            Map<String, List<Emply>> groupEmplyList = emplyList.stream().collect(Collectors.groupingBy(Emply::getSysNo));

            //根据所有人员遍历
            for (Map.Entry<String, List<Emply>> map : groupEmplyList.entrySet()) {

                List<AttendanceRecord> attendanceRecords = deptGroupInfo.get(map.getKey());
//                    Map<String, List<AttendanceRecord>> attendanceRecordMap = new HashMap<>();
                try {
                    if(attendanceRecords != null && attendanceRecords.size() > 0){
//                            attendanceRecordMap = attendanceRecordList.stream().sorted(Comparator.comparing(AttendanceRecord::getCardTime)).collect(Collectors.groupingBy(AttendanceRecord::getSysNo));
                        attendanceRecords = attendanceRecords.stream().sorted(Comparator.comparing(AttendanceRecord::getCardTime)).collect(Collectors.toList());
                    }
                    for (Emply p: map.getValue()) {
//                            List<AttendanceRecord> attendanceRecords = attendanceRecordMap.get(p.getSysNo());
                        Statistics statistics = new Statistics();
                        statistics.setSysNo(p.getSysNo());
                        statistics.setDeptId(p.getDepartId());//部门ID
                        statistics.setDeptName(p.getDepartName());//部门名称
                        statistics.setEmployeeId(p.getEmployeeId());//员工ID
                        statistics.setEmpName(p.getEmployeeName());//员工姓名
                        statistics.setCalDate(DateUtils.parseDate(DateUtils.getNowDate()));//打卡日期
                        statistics.setCalDateText(DateUtils.getDate());
                        if(attendanceRecords != null && attendanceRecords.size() > 0){
                            AttendanceRecord first = attendanceRecords.get(0);
                            AttendanceRecord end = null;
                            if(attendanceRecords.size() > 1){
                                end = attendanceRecords.get(attendanceRecords.size() - 1);
                                statistics.setDrawtmbgn(first.getCardTime());//上班打卡时间
                                statistics.setDrawtmend(end.getCardTime());//下班打卡时间
                                statistics.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                statistics.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, end.getCardTime()));
                            } else {

                                statistics.setStatus(2);//异常
                                statistics.setStatusText("异常");
                                end = first;
                                //判断未签入/未签出
                                if(judegStatus(first.getCardTime())){
                                    statistics.setDrawtmbgnText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                    statistics.setDrawtmendText("未签出");
                                } else {
                                    statistics.setDrawtmendText(DateUtils.parseDateToStr(DateUtils.HH_MM_SS, first.getCardTime()));
                                    statistics.setDrawtmbgnText("未签入");
                                }
                            }
                            long min = DateUtils.getMin(end.getCardTime(), first.getCardTime());
                            statistics.setFactGs((int)min);

                            if(judegDate(first.getCardTime(), end.getCardTime()) && min >= 510){
                                statistics.setStatus(1);
                                statistics.setStatusText("正常");
                            } else {
                                statistics.setStatus(2);
                                statistics.setStatusText("异常");
                            }
                        } else {
                            statistics.setDrawtmendText("未签出");
                            statistics.setDrawtmbgnText("未签入");
                            statistics.setStatus(2);
                            statistics.setStatusText("异常");
                            statistics.setFactGs(0);
                        }
                        statistics.setIsWeekend(holidays.getType() == 0 ? "否" : "是");
                        if(holidays.getType() == 0){
                            statistics.setRemark("工作日");
                        }
                        if(holidays.getType() == 1){
                            statistics.setRemark("周末");
                        }
                        if(holidays.getType() == 2){
                            statistics.setRemark("节假日");
                        }
                        attendanceStatisticsList.add(statistics);
                    };

                    System.out.println("共" + attendanceStatisticsList.size() + "条数据");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return attendanceStatisticsList;

        }
        return null;
    }

    public boolean judegDate(Date startDate, Date endDate){
        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startDate);
        Date startWorkDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 09:00:59");
        Date endWorkDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 17:00:00");
        if(startDate.getTime() <= startWorkDate.getTime() && endDate.getTime() >= endWorkDate.getTime()){
            return true;
        } else {
            return false;
        }
    }

    public boolean judegStatus(Date startDate){
        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startDate);
        Date endWorkDate = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 17:00:00");

        if(startDate.getTime() < endWorkDate.getTime()){
            return true;
        } else {
            return false;
        }
    }
}
